import { getCurrentShift, getTaskDetail, type uploadImageType } from '@/apis/index'
import { baseApi, type RequestCode } from '@/server/base'
import { getNowDateTime } from '@/utils/index'
import { Notify, Toast, Dialog, type NotifyOptions, type ToastOptions } from 'vant'
import { type LoginUser } from '@/server'
import taskFactory from '@/utils/task'
import { getHomeStatistics } from '@/apis/index'
import { type BaseSystemInfo } from '@/server/android-vue'

const { pushLoopTask, pushLoopTaskList, executeLoopTask, clearTask } = taskFactory()

type statisticsType = {
  pending: number
  running: number
  cancel: number
  completed: number
  completd: number
}

declare const process: any

export default {
  props: {
    goBackPage: Function
  },
  data() {
    return {

      shiftInfo: {} as any,
      currentDate: getNowDateTime(),
      userName: (this as any).$store.getters['user/username'],
      carId: (this as any).$store.getters['user/carId'],
      account: (this as any).$store.getters['user/account'],
      userInfo: (this as any).$store.getters['user/userInfo'] as LoginUser,

      /**
       * 任务详情
       */
      taskDetailInfo: {} as any,

      statistics: {
        pending: 0,
        running: 0,
        cancel: 0,
        completed: 0,
        completd: 0
      } as statisticsType,
      isFirstGetStatistics: true
    } as any
  },
  computed: {
    isDevelopment() {
      try {
        return (process as any).env.NODE_ENV !== 'production'
      } catch (error) {
        return false
      }
    }
  },
  methods: {
    /**
     * 获取图片路径
     * @param img
     */
    getImageFilePath(img: uploadImageType): string {
      return `${baseApi}/${img.disk}/${img.path}`
    },
    /**
     * 定时任务
     */
    pushLoopTask,
    pushLoopTaskList,
    executeLoopTask,
    clearTask,

    getUserInit() {
      const that = this as any
      that.userName = that.$store.getters['user/username']
      that.carId = that.$store.getters['user/carId']
      that.account = that.$store.getters['user/account']
      that.userInfo = that.$store.getters['user/userInfo']
    },

    showToast(option: string | ToastOptions) {
      Toast(option)
    },
    showNotify(options: number | string | NotifyOptions) {
      Notify(options)
    },

    /**
     * 获取state 对应的状态
     * @param value
     * @returns
     */
    getTaskCodeByState(state?: string | number, cancel_state?: string | number) {
      if (cancel_state != undefined && +cancel_state > 0) {
        const { text, code } = this.getCancelOrTransferState(cancel_state)
        return {
          text,
          code,
          classCode: 'task-cancel'
        }
      }
      state = state || 0
      if (
        [
          '1', //待接单
          '2', // 进行中
          '3', //已完成
          '4' //已取消
        ].includes(state + '')
      ) {
        const stateType = ['', '待接单', '进行中', '已完成', '已取消']
        const stateCode = ['', 'wait', 'going', 'completed', 'cancel']
        const code = stateCode[+state]
        return {
          text: stateType[+state],
          code: code,
          classCode: 'task-' + code
        }
      }
      return {
        text: '',
        code: '',
        classCode: ''
      }
    },

    getCancelOrTransferState(cancel_state: string | number) {
      if (!cancel_state && cancel_state != 0) {
        return {
          text: '',
          code: ''
        }
      }
      cancel_state = +cancel_state || 1
      const texts = ['', '申请取消', '申请转交', '取消通过', '转交通过']
      const codes = [
        '',
        'cancel',
        'transfer',
        'canceled',
        'transferred',
        'cancel_reject',
        'transfer_reject'
      ]
      return {
        text: texts[cancel_state],
        code: codes[cancel_state]
      }
    },
    /**
     * 获取当前 班
     */
    getSystemCurrentShift() {
      getCurrentShift()
        .then((res: RequestCode) => {
          ; (this as any).shiftInfo = res.data
        })
        .catch(error => {
          console.log(error)
        })
    },
    goRouterPage(router: any, reload: boolean = false) {
      ; (this as any).$router.push(router)
      if (reload) {
        setTimeout(() => {
          this.goBackOrForward(0)
        }, 200)
      }
    },
    /**
     * 前进或后退
     * @param go 负值后退，正值前进 0时刷新
     * @param reload 是否刷新
     * @returns
     */
    goBackOrForward(go: number = -1, reload: boolean = false) {
      if (go === 0) {
        window.location.reload()
        return
      }
      const position = window.history.state.position + go

      // if (position > window.history.length) {
      //   Toast('已经到达最顶层！')
      //   return
      // }
      if (position < 0) {
        Toast('已经退到最低层！')
        return
      }
      window.history.go(go)
      if (reload) {
        setTimeout(() => {
          window.location.reload()
        }, 200)
      }
    },
    /**
     * 获取对应值的优先级标签
     * @param value
     * @returns
     */
    getUrgentValue(value: number | string) {
      //value 1 2 3
      value = value || 1
      return ['Default', 'Urgent', 'SOS'][+value - 1]
    },

    /**
     * 获取 对象 转成字符串
     * @param item
     * @returns
     */
    getParamsString(item: any) {
      return encodeURI(JSON.stringify(item))
    },
    /**
     * 获取字符串转成对象
     * @param itemStr
     * @returns
     */
    getParamsByString(itemStr: string) {
      return JSON.parse(decodeURI(itemStr))
    },

    /**
     *
     * @param id
     */
    getTaskDetailById(id: string | number, successFn?: Function | undefined) {
      getTaskDetail(id)
        .then((res: RequestCode) => {
          ; (this as any).taskDetailInfo = res.data
          if (typeof successFn == 'function') {
            successFn()
          }
        })
        .catch(error => { })
    },

    getStatistics() {
      const that = this as any
      if (!that.userInfo) {
        return
      }
      getHomeStatistics().then(res => {
        that.sendNotifyNumber(res.data)
        that.statistics = res.data as statisticsType
      })
    },
    sendNotifyNumber(data: statisticsType) {
      //获取数据和旧数据进行比对，如果出现多出的则提示
      if (this.isToastNewMessage((this as any).statistics, data)) {
        console.log('准备发送消息')
        try {
          ; (this as any).$native.showNotify('通知', `${getNowDateTime(0)}：你有新任务待处理！`)
          console.log(
            '🚀 ~ file: index.vue:136 ~ getHomeStatistics ~ 发现新消息，进行通知:',
            `${getNowDateTime(0)}：你有新任务待处理！`
          )
        } catch (error) { }
      }
    },
    isToastNewMessage(oldRes: statisticsType, newRes: statisticsType) {
      /**
       * 首次使用不提示
       */
      if ((this as any).isFirstGetStatistics) {
        ; (this as any).isFirstGetStatistics = false
        return false
      }

      return (
        newRes.pending > oldRes.pending ||
        newRes.running > oldRes.running ||
        newRes.cancel > oldRes.cancel ||
        newRes.completd > oldRes.completd
      )
    },

  },
  created() {
    ; (this as any).getSystemCurrentShift()
      ; (this as any).getUserInit()
      ; (this as any).getStatistics()
    pushLoopTask({
      //添加定时获取时间
      method: () => {
        ; (this as any).currentDate = getNowDateTime()
      },
      immediate: true,
      interval: 1000 * 60,
      name: 'System-current-time'
    })
    //定時獲取任務列表
    pushLoopTask({
      method: () => {
        ; (this as any).getStatistics()
      },
      immediate: true,
      interval: 1000 * 60,
      name: 'System-home-statistics-task'
    })
    executeLoopTask(true)
  },
  destroyed() {
    executeLoopTask(false)
    clearTask()
  }
}
